package com.douguo.recipe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.Caipu;
import com.douguo.recipe.object.Favor;
import com.douguo.recipe.provider.DBHelper;
import com.douguo.recipe.view.NavigationView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class FavorActivity extends DouguoActivity {

	// --------------ui--------------
	private ListView mListView;
	private NavigationView mNavigation;
	private Button mBtnBack;
	// ------------------------------
	// ------------adapter-----------
	private MultiChoiceCursorAdapter mAdapter;
	// ------------------------------

	// -------------dbHelper---------
	private DBHelper mDbHelper;
	// ------------------------------
	// -------------data-------------
	private List<Map<String, Object>> mCaipus;

	// ------------------------------

	// // -------------mode--------------
	// private static final int MODE_NORMAL = 0;
	// private static final int MODE_SELECT = 1;
	// private int mMode = MODE_NORMAL;
	// // --------------------------------
	// -------------menuid-------------
	private static final int MENU_SELECT_ALL = Menu.FIRST;
	private static final int MENU_SELECT_NOT = Menu.FIRST + 1;
	private static final int MENU_CONFIRMDEL = Menu.FIRST + 2;
	private static final int MENU_EDIT = Menu.FIRST + 3;
	private static final int MENU_EDIT_EXIT = Menu.FIRST + 4;

	private static final int MENU_VIEW_RECIPE = Menu.FIRST + 5;
	private static final int MENU_DEL_RECIPE = Menu.FIRST + 6;
	private static final int MENU_HOME = Menu.FIRST + 7;
	// --------------------------------

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favor);
		mDbHelper = new DBHelper(this);

		initUI();
		initData();

	}

	@Override
	public void onResume() {
		super.onResume();
		updateData();

	}

	private void startRecipeActivity(int pos) {
		Intent intent = new Intent(FavorActivity.this, RecipeActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("recipeId", (String) mCaipus.get(pos).get("favorId"));
//		bundle.putString("recipePicPath", (String) mCaipus.get(pos).get("favorId"));
		bundle.putInt("pos", pos);
		int[] ids = new int[mCaipus.size()];
		int i = 0;
		for (; i < mCaipus.size(); ++i) {
			ids[i] = Integer.valueOf((String) mCaipus.get(i).get("favorId"));
		}
		bundle.putIntArray("ids", ids);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	public void initUI() {
		mListView = (ListView) findViewById(R.id.list_favor);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {
				if (mAdapter.getMode() == MultiChoiceCursorAdapter.MODE_SELECT) {
					mAdapter.selectItem(pos);
				} else if (mAdapter.getMode() == MultiChoiceCursorAdapter.MODE_NORMAL) {
					startRecipeActivity(pos);
				}
			}
		});

		mListView
				.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

					public void onCreateContextMenu(ContextMenu menu, View v,
							ContextMenuInfo menuInfo) {
						menu.clear();
						menu.add(0, MENU_VIEW_RECIPE, 0, R.string.viewRecipe);
						menu.add(0, MENU_DEL_RECIPE, 0, R.string.delFavor);
					}
				});

		mNavigation = new NavigationView(this,NavigationView.STATE_MORE);
		mBtnBack = (Button) findViewById(R.id.imageButton_back);
		mBtnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
		setTitle(getString(R.string.titleWoDeShouCang));
	}

	public void initData() {
		mCaipus = new ArrayList<Map<String, Object>>();
		// updateData();
		mAdapter = new MultiChoiceCursorAdapter(this, mCaipus,
				R.layout.favorlist_listitem, new String[] { "recipeName",
						"recipeMajor", "recipeAuthor", "recipeMinor",
						"recipePic", "favorId" }, new int[] { R.id.recipeName,
						R.id.recipeMajor, R.id.recipeAuthor, R.id.recipeMinor,
						R.id.recipeImg });
		mAdapter.setViewBinder(new ViewBinder() {

			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (view instanceof TextView) {
					TextView tv = (TextView) view;
					tv.setText(textRepresentation);
				} else if (view instanceof ImageView) {
					ImageView img = (ImageView) view;
					img.setImageBitmap((Bitmap) data);
					// img.setImageResource(R.drawable.gallery1);
				}
				return true;// must be true
			}

		});

		mListView.setAdapter(mAdapter);
	}

	private void updateData() {
		mCaipus.clear();
		List<Favor> favors = mDbHelper.getFavors();
		for (Favor favor : favors) {
			Caipu caipu;
			caipu = mDbHelper.getRecipe(favor.mFavorId);
			HashMap<String, Object> hmap = new HashMap<String, Object>();
			if (caipu != null) {

				hmap.put("recipeName", caipu.name);
				hmap.put("recipeMajor", getResources()
						.getString(R.string.major) + ": " + caipu.major);
				hmap.put("recipeAuthor",
						getResources().getString(R.string.author) + ": "
								+ caipu.author);
				hmap.put("recipeMinor", getResources()
						.getString(R.string.minor) + ": " + caipu.minor);
				Bitmap bitmap = Util.read80X80BitmapFromSDCard(caipu.thumbPath);
				if (bitmap == null) {
					bitmap = BitmapFactory.decodeResource(getResources(),
							R.drawable.cookdefault80);
				}
				hmap.put("recipePic", bitmap);
				hmap.put("favorId", favor.mFavorId);
				mCaipus.add(hmap);
			}
		}
		mAdapter.notifyDataSetChanged();
	}

	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		if (mAdapter.getMode() == MultiChoiceCursorAdapter.MODE_SELECT) {
			menu.add(0, MENU_SELECT_ALL, 0, R.string.selectAll);
			menu.add(0, MENU_SELECT_NOT, 0, R.string.selectNot);
			menu.add(0, MENU_EDIT_EXIT, 0, R.string.exitEditFavor);
			menu.add(0, MENU_CONFIRMDEL, 0, R.string.confirmDel);
		} else if (mAdapter.getMode() == MultiChoiceCursorAdapter.MODE_NORMAL) {
			menu.add(0, MENU_EDIT, 0, R.string.editFavor);
			menu.add(0, MENU_HOME, 0, R.string.backToHome);
		}
		return true;
	}

	private void delFavor() {
		List<Long> favorIds = mAdapter.getSelected();
		for (long id : favorIds) {
			mDbHelper.deleteFavor(id);
		}
		
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		int i = 0;
		switch (item.getItemId()) {
		case MENU_HOME:
			Intent homeIntent = new Intent(this, HomeActivity.class);
			homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(homeIntent);
			break;
		case MENU_CONFIRMDEL:
			delFavor();
			updateData();
			mAdapter.clear();
			mAdapter.notifyDataSetChanged();
			break;
		case MENU_SELECT_ALL:
			mAdapter.selectAll();
			break;
		case MENU_SELECT_NOT:
			mAdapter.unSelect();
			break;
		case MENU_EDIT:
			mAdapter.setMode(MultiChoiceCursorAdapter.MODE_SELECT);
			openOptionsMenu();
			break;
		case MENU_EDIT_EXIT:
			mAdapter.setMode(MultiChoiceCursorAdapter.MODE_NORMAL);
			openOptionsMenu();
			break;
		}
		return true;
	}

	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case MENU_VIEW_RECIPE:
			startRecipeActivity(info.position);
			break;
		case MENU_DEL_RECIPE:
			mDbHelper.deleteFavor(Long.valueOf((String) mCaipus.get(
					info.position).get("favorId")));
			updateData();
			mAdapter.clear();
			mAdapter.notifyDataSetChanged();
			break;
		}
		return true;

	}

	class MultiChoiceCursorAdapter extends SimpleAdapter {
		public static final int MODE_NORMAL = 0;
		public static final int MODE_SELECT = 1;
		public int mMode;
		public boolean[] isChecked;
		CheckBox mCheckBox;
		private List<? extends Map<String, ?>> mData;

		public MultiChoiceCursorAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
			mData = data;
			mMode = MODE_NORMAL;
		}

		public boolean isSelectMode() {
			return mMode == MODE_SELECT;
		}

		public boolean isNormalMode() {
			return mMode == MODE_NORMAL;
		}

		public void setMode(int m) {
			mMode = m;

			if (m == MODE_SELECT)
				clear();
			notifyDataSetInvalidated();
		}

		public int getMode() {
			return mMode;
		}

		private void clear() {
			isChecked = new boolean[mData.size()];
			for (int i = 0; i < mData.size(); i++) {
				isChecked[i] = false;
			}
		}

		public boolean selectItem(int position) {
			int i = position;
			isChecked[i] = !(isChecked[i]);
			notifyDataSetInvalidated();
			return isChecked[i];
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			mCheckBox = (CheckBox) view.findViewById(R.id.checkbox);
			if (mMode == MODE_NORMAL) {
				mCheckBox.setVisibility(View.GONE);
			} else {
				mCheckBox.setVisibility(View.VISIBLE);
				mCheckBox.setFocusable(false);
				if (isChecked[position]) {
					mCheckBox.setChecked(true);
				} else {
					mCheckBox.setChecked(false);
				}
			}
			return view;
		}

		public List<Long> getSelected() {
			List<Long> selectedItems = new ArrayList<Long>();
			for (int i = 0; i < mData.size(); i++) {
				if (isChecked[i]) {
					selectedItems.add(Long.valueOf((String) mData.get(i).get(
							"favorId")));
				}
			}
			return selectedItems;
		}

		public boolean checkSelected() {
			for (int i = 0; i < mData.size(); i++) {
				if (isChecked[i]) {
					return true;
				}
			}

			return false;
		}

		public void selectAll() {
			for (int i = 0; i < mData.size(); i++) {
				isChecked[i] = true;
			}
			notifyDataSetInvalidated();
		}

		public void unSelect() {
			for (int i = 0; i < mData.size(); i++) {
				isChecked[i] = false;
			}
			notifyDataSetInvalidated();
		}

	}
}
